package org.wizehack.mri;

import org.wizehack.mri.fl.SFLAlgorithm;
import org.wizehack.mri.repo.MongoDBAccessPoint;

import com.mongodb.DBCursor;
import com.mongodb.DBObject;

class BugAnalysisThread implements Runnable {

	private SFLAlgorithm algorithm;
	private int[] totalPassed;
	private int[] totalFailed;
	private int testSUite;
	private boolean[][] isPassed;
	private String sourceCodeId;
//	private String code;
//	private int number;
	
	private MongoDBAccessPoint dbap = MongoDBAccessPoint.getInstance();
	
	public BugAnalysisThread(SFLAlgorithm algorithm,
			int[] totalPassed, int[] totalFailed, int testSUite,
			boolean[][] isPassed, String sourceCodeId) {
	
		this.algorithm = algorithm;
		this.totalPassed = totalPassed;
		this.totalFailed = totalFailed;
		this.testSUite = testSUite;
		this.isPassed = isPassed;
		this.sourceCodeId = sourceCodeId;
//		this.code = code;
//		this.number = number;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		DBCursor covCursor = dbap.getDocumentsFromCoverage(sourceCodeId, testSUite);
		int passed = 0;
		int failed = 0;
		double sus = 0;
		String file = null;
		String code = null;
		int number = 0;
		if(covCursor != null){
			try{
				
				while(covCursor.hasNext()){

					DBObject covDBObj = covCursor.next();

					int testCase = (int) covDBObj.get("test_case")-1;
					file = covDBObj.get("file_name").toString();
					code = covDBObj.get("code").toString();
					number = (int) covDBObj.get("number");
//					System.out.println(isPassed + " " + isPassed[testSUite-1][testCase]);
					if(isPassed[testSUite-1][testCase]){
						passed++;
//						if(number == 12){
//							System.out.println("passed: " + code);
//							System.out.println("passed: " + testCase);
//						}
					} else {
						failed++;
//						if(number == 12){
//							System.out.println("failed: " + code);
//							System.out.println("failed: " + testCase);
//						}
					}
				}//end while
										
				sus = algorithm.getSuspiciousness(totalPassed[testSUite-1], totalFailed[testSUite-1], passed, failed);
				if(number == 12){
					System.out.println("total passed: " + totalPassed[testSUite-1]);
					System.out.println("total failed: " + totalFailed[testSUite-1]);

					System.out.println("passed: " + passed);
					System.out.println("failed: " + failed);
					System.out.println("sus: " + sus);

				}
				if(sus > 0) { 				// sus 입력
					dbap.insertDataToSuspiciousness(file, sourceCodeId.toString(), code, number, testSUite, sus);
				}				
				
			} finally {
				covCursor.close();
			}
		} //end if
	}

}
